package com.ra.landlord;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.da.landlord.DaAgreement;
import com.da.landlord.DaChargeBill;
import com.da.landlord.DaChargeItem;
import com.da.landlord.DaRoom;
import com.da.landlord.DaRoomService;
import com.espirit.eap.util.StatGenericJPAService;
import com.espirit.weixin.core.WeixinConfig;
import com.espirit.weixin.core.WeixinUtil;
import com.googlecode.cswish.Config;
import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.oosearch.Condition;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.ContextHolder;
import com.googlecode.cswish.struts.spring.SystemEnv;
import com.googlecode.cswish.util.Functions;
import com.googlecode.cswish.util.bean.ModelUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Result;
import com.ra.external.BuildingInfoService;
import com.ra.external.QRLimitSceneService;
import com.ra.external.RentalOrderService;
import com.ra.external.RoomRetrievalService;
import com.ra.external.ServiceInfoService;
import com.ra.external.WeixinService;
import com.ra.landlord.BuildingFloorRoomVO.SimpleBuild;
import com.ra.landlord.BuildingFloorRoomVO.SimpleDaRoom;
import com.ra.landlord.BuildingFloorRoomVO.SimpleFloor;
import com.ra.landlord.BuildingFloorRoomVO.SimpleRoomVO;
import com.ra.landlord.constant.LandlordConstant;
import com.ra.landlord.constant.RoomType;
import com.ra.system.Version;
import com.ra.util.Address;
import com.ra.util.AddressService;
import com.ra.util.DateTimeUtil;
import com.ra.util.PrinterService;
import com.ra.util.QRCodeService;

/**
 * 楼房服务
 * 
 * @author colin
 * @date 2014年9月20日
 *
 */
@Service
public class BuildingService {

	private static final Log logger = LogFactory.getLog(BuildingService.class);
	
	@Resource
	private StatGenericJPAService genericService;
	
	@Resource
	private LandlordUserService landlordUserService;
	
	@Resource
	private BuildingFloorService buildingFloorService;
	
	@Resource
	private AddressService addressService;
	
	@Resource
	private WeixinUtil weixinUtil;
	
	@Resource
	private QRCodeService qrCodeService;
	
	@Resource
	private QRLimitSceneService qrLimitSceneService;
	
	@Resource
	private PrinterService printerService;
	
	@Resource
	private Config config;
	
	@Resource
	private Functions functions;

	@Resource
	private ServiceInfoService serviceInfoService;
	
	@Resource
	private RoomService roomservice;
	
	@Resource
	private RoomRetrievalService retrievalService;
	
	@Resource
	private DaRoomService daRoomService;
	
	@Resource
	private BuildingInfoService buildingInfoService;
	
	@Resource
	private RoomRetrievalService roomRetrievalService;
	
	@Resource
	private RentalOrderService rentalOrderService;
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@Rest(type="search")
	public Building getBuilding(Building model, boolean showUrl) {
		Building building = genericService.load(model);
		
//		if (building != null && showUrl) {
//			boolean isEclipseEnv = "true".equals(System.getProperty(SystemEnv.RUNNING_IN_ECLIPSE));
//			boolean isCrm = "fxcrm".equals(ContextHolder.get().getSiteName());
//			if (isEclipseEnv || isCrm) {
//				Integer sceneId = qrLimitSceneService.applySceneId(WeixinService.LIMIT_SUBSCRIBE_KEY_SHOWBUILDING, String.valueOf(building.getId()));
//				String url = weixinUtil.createQRCode(null, sceneId, WeixinService.LIMIT_SUBSCRIBE_KEY_SHOWBUILDING, null);
//				ActionContext.getContext().getValueStack().setValue("url", url);
//			}
//		}
		return building;
	}
	
	/**
	 * 生成单个楼房二维码图片
	 * @param model
	 * @param siteUrl
	 * @param url
	 * @param width
	 * @param height
	 * @return
	 */
	@Rest(type = "print")
	private String printSingleBuilding(Building model,String siteUrl, int width, int height, int times){
		Building dbBuilding = genericService.load(model, false);
		if (dbBuilding == null) {
			return null;
		}
		
		String picPathName = "";
		String siteUrlEncoder = "";
		try {
			siteUrlEncoder = URLEncoder.encode(siteUrl, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("Failed to encode parameter: " + siteUrl, e);
		}
		String url = "/ra/landlord/building.getBuilding.html?model.id=" + model.getId() + "&pathPrefix=" + siteUrlEncoder;
		if (width == 0) {
			width = 3579;
		}
		if (height == 0) {
			height = 5071;
		}
		if (times <= 0) {
			times = 1;
		}
		
		String cachePath = config.getRealSiteTmpPath("buildingPicCache");
		
		File picFile = new File(cachePath, "building_" + model.getId() + '_' + times + ".jpg");
		boolean success = false;
		
		success = printerService.generateImage2File(url, width, height, times, picFile);
		
		if (success || picFile.exists()) {
			String pathName = picFile.getPath();
			int beginIndex = pathName.indexOf("site" + File.separator + ContextHolder.get().getSiteName());
			pathName = pathName.substring(beginIndex);
			picPathName = siteUrl + pathName;
			if (logger.isDebugEnabled()) {
				logger.debug("generate the building picture " + picFile.getPath());
			}
		}
		return picPathName;
	}
	
	/**
	 * 生成楼房二维码图片，如果model为null，则生成当前房东所有楼房二维码，否则则生成指定楼房二维码
	 * @param model
	 * @param width
	 * @param height
	 * @return
	 */
	@Rest(type = "print")
	public String[] printBuilding(Building model, int width, int height, int times){
		String[] picPathNames = new String[1];
		boolean isEclipseEnv = "true".equals(System.getProperty(SystemEnv.RUNNING_IN_ECLIPSE));
		String siteUrl;
		
		if (isEclipseEnv) {
			siteUrl = "http://localhost:8080/";
		} else {
			siteUrl = weixinUtil.getWeixinConfig().getServerSiteName() + "/";
		}
		
		if (model==null || model.getId() == null) {
			List<Building> buildings = searchBuilding();
			if (buildings != null && buildings.size() > 0) {
				picPathNames = new String[buildings.size()];
				for (int i = 0; i < buildings.size(); i++) {
					Building building = buildings.get(i);
					picPathNames[i] = printSingleBuilding(building, siteUrl, width, height, times);
				}
			}
		} else if(model.getId() != null){
			picPathNames[0] = printSingleBuilding(model, siteUrl, width, height, times);
		}
		for (int i = 0; i < picPathNames.length; i++) {
			String pathName = picPathNames[i];
			pathName = pathName.replace('\\', '/');
			picPathNames[i] = pathName;
		}
		return picPathNames;
	}
	
	@Rest(type = "print")
	public Result downloadBuildingPrinter(Building model, int times) throws Exception {
		int width = 3579;
		int height = 5071;
		String path = printBuilding(model, width, height, times)[0];
		int beginIndex = path.indexOf("site" + File.separator + ContextHolder.get().getSiteName());
		String name = path.substring(beginIndex - 1).replace('\\', '/');
		
		Building dbBuilding = genericService.load(model, false);
		String buildingName = dbBuilding.getName() + ".jpg";
		return genericService.viewFile(name, buildingName);
	}
	
	@Transactional
	@Rest(type="add")
	public Building add(Building model) {
		return addBuilding(model);
	}
	
	@Transactional
	@Rest(type="add")
	public Building addBuildingAndRoom(Building model, String roomInfos){
		//需要传地址过来
		
		// 电梯
		model.setElevator(true);
		if (model.getFloorCount() != null && model.getFloorCount() < 8) {
			model.setElevator(false);
		}
		
		//电话
		LandlordOwnerUser landlordOwnerUser = genericService.load(landlordUserService.getLoginUser().getOwnerUser());
		model.setPhoneNum(landlordOwnerUser.getPhone());
		
		// 建楼年份，默认为当年
		Calendar calendar = Calendar.getInstance();
		model.setBuildingTime(DateTimeUtil.formatDateTime(calendar.getTime(), "yyyy"));
		
		// 押付方式，默认为押一付一
		model.setRentPayMode(LandlordConstant.ROOM_RENTTYPE_1T1);
		
		// 0为1个月
		model.setRentCycle(0);
		model.setDetailAddress(model.getAddress().getName());
	
		
		//创建楼
		Building building = addBuilding(model);
		
		List<BuildingFloor> floors = building.getBuildingFloors();
		
		if (StringUtils.isNotBlank(roomInfos)) {
			List<Room> rooms = new ArrayList<>();
			String[] arrRoomInfo = roomInfos.split(",");
			if (arrRoomInfo.length > 0) {
				for (int i = 0; i < arrRoomInfo.length; i++) {
					Room roomModel = new Room();
					String[] floorRoom = arrRoomInfo[i].split("_");
					if (floorRoom.length < 2) {
						continue;
					}
					roomModel.setName(floorRoom[1]);
					Integer floorCount = Integer.parseInt(floorRoom[0]);
					roomModel.setBuildingFloor(floors.get(floorCount - 1));
					roomModel.setRoomType(RoomType.RTM_1R_0H);
					roomModel.adaptRoomType();
					roomModel.setPurpose(0);
					roomModel.setArea(new BigDecimal(50));
					roomModel.setBuilding(building);
					Room room = roomservice.addRoomBatchNotPublish(roomModel);
					rooms.add(room);
				}
			}
			
			building.setRooms(rooms);
		}
		
		// 批量发布房源
		roomRetrievalService.batchPublishRooms(building.getRooms(), false);
		return building;
	}
	
	@Transactional
	@Rest(type="add")
	public Building addBuilding(Building model) {
		// set the landlord user in advance, let the 'add' method to update the parent/child relationship
		LandlordOwnerUser landlordOwnerUser = genericService.load(landlordUserService.getLoginUser().getOwnerUser());
		//ModelUtil.copy(landlordUserService.getLoginUser().getOwnerUser(), landlordUser);
		List<LandlordUser> landlordUsers = new ArrayList<>();
		model.setLandlordUser(landlordOwnerUser);
		landlordUsers.add(landlordOwnerUser);
		model.setLandlordUsers(landlordUsers);
		if (landlordOwnerUser.getBuildings() == null) {
			landlordOwnerUser.setBuildings(new ArrayList<Building>());
		}
		landlordOwnerUser.getBuildings().add(model);
		// 暂时无用
		//model.setPublish(true);
		//新建楼房，房间数为0
		model.setRoomCount(0);
		
		//新增的地址同时，给出一个区域，该区域待优化，应该给一个默认省市区域相同的区域
		Zone zone = null;
		Address address = model.getAddress();
		
		address = addressService.completeAddress(address);
		
		zone = addressService.getZone(address);
		
		if (zone != null) {
			address.setZone1(zone);
		}else{
			// 给个默认的区域
			zone = new Zone();
			String zoneName = addressService.getFirstAddress(model.getAddress());
			zone.setName(zoneName);
			address.setZone1(zone);
		}
		
		List<BuildingFloor> lstBuildingFloor = new ArrayList<>();
		if (model.getFloorCount() > 0 ) {
			for (int i = 0; i < model.getFloorCount(); i++) {
				BuildingFloor floor = new BuildingFloor();
				floor.setName("第"+(i+1)+"层");
				floor.setNo((i+1));
				floor.setBuilding(model);
				// 默认为0，暂不知作何用
				floor.setType(0);
				lstBuildingFloor.add(floor);
			}
		}
		model.setBuildingFloors(lstBuildingFloor);
		
		Building result = genericService.merge(model);
		serviceInfoService.batchAddServiceInfosFromBaidu(result.getId());
		return result;
	}
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@Rest(type="update")
	@Transactional
	public Building updateBuilding(Building model) {
		
		Building building = genericService.load(model);
		Address address = model.getAddress();
		if (address != null) {
			address = addressService.completeAddress(address);
			if (model.getAddress().getId() != null) {
				address = genericService.load(model.getAddress());
				building.setAddress(address);
			}else{
				if (address != null && address.getAddressCode() != null && address.getAddressCode().getId() != null) {
					building.setAddress(address);
					building.setDetailAddress(address.getName());
				}
			}
		}
		building.setName(model.getName());
		building.setPhoneNum(model.getPhoneNum());
		//building.setBuildingTime(model.getBuildingTime());
		//building.setFloorCount(model.getFloorCount());
		building.setElevator(model.getElevator());
		building.setRentPayMode(model.getRentPayMode());
		building.setRentCycle(model.getRentCycle());
		
		if(!building.getFloorCount().equals(model.getFloorCount()))
		{
			//只有大于它才增加，小于它，就跳过。
			if(building.getFloorCount() < model.getFloorCount())
			{
				//Note: building.getBuildingFloors().size() 不能注释，专门加上为了解决重复新增楼层问题
				building.getBuildingFloors().size();
				
				//hbernate只有才原有的基础上才可以操作级联集合。
				//List<BuildingFloor> newBuildingFloors = new ArrayList<>();
				int indexBegin = building.getFloorCount() + 1;
				for (int i = indexBegin; i <= model.getFloorCount(); i++) {
					BuildingFloor floor = new BuildingFloor();
					floor.setName("第" + i + "层");
					floor.setNo((i));
					floor.setBuilding(building);
					
					// 默认为0，暂不知作何用
					floor.setType(0);
					
					building.getBuildingFloors().add(floor);
					
					//newBuildingFloors.add(floor);
				}
				building.setFloorCount(model.getFloorCount());
				//building.getBuildingFloors().addAll(newBuildingFloors);
			}
		}
		
		building = genericService.merge(building);
		
		try {
			//如果需要推广，则自动发布推广
			buildingInfoService.updateBuildingInfoAsync(building);
		} catch (Exception e) {
			logger.error("update published buildinginfo error after update building!",e);
		}
			
		return building;
	}
	
	@Rest(type="delete")
	@Transactional
	public boolean deleteBuilding(List<Building> buildings) {
		
		if (buildings != null && buildings.size() > 0) {
			for (Building building : buildings) {
				if (building.getId() == null)
				{
					continue;
				}
				Building queryModel = new Building();
				queryModel.setId(building.getId());
				Building dbBuilding =  genericService.load(queryModel, false);
				//genericService.delete(dbBuilding);
				dbBuilding.setStatus(Version.STATUS_INVALID);
				if (dbBuilding.getRooms() != null) {
					for (Room room : dbBuilding.getRooms()) {
						room.setStatus(Version.STATUS_INVALID);
						if (room.getAgreement() != null) {
							room.getAgreement().setStatus(Version.STATUS_INVALID);
						}
					}
				}
				//删除楼房对应的buildingInfo,roomInfo
				buildingInfoService.deleteBuildingInfo(building.getId());
				//删除楼对应的订单
				rentalOrderService.deleteRentalOrderByBuilding(building.getId());
			}
		}
		
		return true;
	}
	
	@Rest(type="search")
	public List<Building> searchBuilding() {
		Building model = new Building();
		LandlordUser landlordUser = landlordUserService.getLoginUser();
		
		// 房东管理员看自己的
		List<LandlordUser> landlordUsers = new ArrayList<LandlordUser>();
		landlordUsers.add(landlordUser);
		model.setLandlordUsers(landlordUsers);
		
		
		//因为PC端ra_building表未存detailAddress字段，所以需要对List<Building>做处理
		List<Building> lstBuilding = genericService.searchAll(model).getData();
		if (lstBuilding != null) {
			for (Building building : lstBuilding) {
				if (StringUtils.isBlank(building.getDetailAddress()) && building.getAddress() != null) {
					building.setDetailAddress(building.getAddress().getName());
				}
			}
		}
		return lstBuilding;
	}
	
	/**
	 * 查询未收租的房间数
	 * @return
	 */
	@Rest(type="search")
	public int getNotChargeCount(){
		LandlordUser landlordUser = landlordUserService.getLandlordUser();
		LandlordOwnerUser landlordOwnerUser = landlordUserService.getLandlordOwnerUser();
		if (landlordUser instanceof LandlordAssistUser) {
			QLInfo ql2 = new QLInfo("from " + Room.class.getName() + " a inner join a.agreements b with a.rentState=? where a.landlordUser = ? and exists (from a.building.landlordUsers f where f = ?) and not exists (from b.fees c where substr(date_add_interval(c.dateEndRecv, -ifnull(b.advanceNum, 3)), 1, 10) >= substr(?, 1, 10) and c.feeType = ? ) and b.agreementState=? ", false);
			ql2.addParam(Room.RENT_STATE_ALREADY);
			ql2.addParam(landlordOwnerUser);
			ql2.addParam(landlordUser);
			ql2.addParam(DateTimeUtil.formatDate(new Date()));
			ql2.addParam(Fee.FEE_TYPE_RENTAL);
			ql2.addParam(Agreement.AGREEMENT_STATE_VALID);
			return genericService.getCount(ql2, false);
		} else {
			QLInfo ql2 = new QLInfo("from " + Room.class.getName() + " a inner join a.agreements b with a.rentState=? where not exists (from b.fees c where substr(date_add_interval(c.dateEndRecv, -ifnull(b.advanceNum, 3)), 1, 10) >= substr(?, 1, 10) and c.feeType = ? ) and b.agreementState=? ", false);
			ql2.addParam(Room.RENT_STATE_ALREADY);
			ql2.addParam(DateTimeUtil.formatDate(new Date()));
			ql2.addParam(Fee.FEE_TYPE_RENTAL);
			ql2.addParam(Agreement.AGREEMENT_STATE_VALID);
			return genericService.getCount(ql2, false);
		}
	}
	
	/**
	 * 查询未出租的房间数
	 * @return
	 */
	@Rest(type="search")
	public Long getNotRentalCount(){
		LandlordUser landlordUser = landlordUserService.getLandlordUser();
		LandlordOwnerUser landlordOwnerUser = landlordUserService.getLandlordOwnerUser();
		if (landlordUser instanceof LandlordAssistUser) {
			QLInfo ql2 = new QLInfo("select count(a.id) from " + Room.class.getName() +" a where a.rentState = ? and a.status = ? " + "and a.landlordUser = ? and exists (from a.building.landlordUsers b where b = ?)", true);
			ql2.addParam(Room.RENT_STATE_NOYET);
			ql2.addParam(Version.STATUS_VALID);
			ql2.addParam(landlordOwnerUser);
			ql2.addParam(landlordUser);
			return (Long)genericService.searchByQl(ql2, true).getData().get(0);
		} else {
			QLInfo ql2 = new QLInfo("select count(a.id) from " + Room.class.getName() +" a where a.rentState = ? and a.status = ? ", false);
			ql2.addParam(Room.RENT_STATE_NOYET);
			ql2.addParam(Version.STATUS_VALID);
			return (Long)genericService.searchByQl(ql2, true).getData().get(0);
		}
	}
	
	/**
	 * 查询合约到期的房间数
	 * @return
	 */
	@Rest(type="search")
	public Long getExpiredAgreementCount(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		LandlordUser landlordUser = landlordUserService.getLandlordUser();
		LandlordOwnerUser landlordOwnerUser = landlordUserService.getLandlordOwnerUser();
		if (landlordUser instanceof LandlordAssistUser) {
			QLInfo ql2 = new QLInfo("select count(a.id) from " + Room.class.getName() + " a where a.landlordUser = ? and exists (from a.building.landlordUsers f where f = ?) and a.rentState = ? and exists (select b.id from a.agreements b where b.agreementState = ? and b.rentEndDate <= ? )", false);
			ql2.addParam(landlordOwnerUser);
			ql2.addParam(landlordUser);
			ql2.addParam(Room.RENT_STATE_ALREADY);
			ql2.addParam(Agreement.AGREEMENT_STATE_VALID);
			ql2.addParam(DateTimeUtil.formatDate(new Date()));
			return (Long) genericService.searchByQl(ql2, true).getData().get(0);
		} else {
			QLInfo ql2 = new QLInfo("select count(a.id) from " + Room.class.getName() + " a where a.rentState = ? and exists (select b.id from a.agreements b where b.agreementState = ? and b.rentEndDate <= ? )", false);
			ql2.addParam(Room.RENT_STATE_ALREADY);
			ql2.addParam(Agreement.AGREEMENT_STATE_VALID);
			ql2.addParam(DateTimeUtil.formatDate(new Date()));
			return (Long) genericService.searchByQl(ql2, true).getData().get(0);
		}
	}
	
	/**
	 * 该方法的出现主要是应为和searchBuilding()展现不同的数据
	 * @return
	 */
	@Rest(type="search")
	public List<Building> searchBuildingDetail(Building model) {
		//return searchBuilding();
		
		LandlordUser landlordUser = landlordUserService.getLoginUser();
		
		// 房东管理员看自己的
		List<LandlordUser> landlordUsers = new ArrayList<LandlordUser>();
		landlordUsers.add(landlordUser);
		model.setLandlordUsers(landlordUsers);
		
		
		//因为PC端ra_building表未存detailAddress字段，所以需要对List<Building>做处理
		List<Building> lstBuilding = genericService.searchAll(model).getData();
		if (lstBuilding != null) {
			for (Building building : lstBuilding) {
				if (StringUtils.isBlank(building.getDetailAddress()) && building.getAddress() != null) {
					building.setDetailAddress(building.getAddress().getName());
				}
			}
		}
		return lstBuilding;
	}
	
	
	/**
	 * 给指定的楼房ID生成微信公共号的关注二维码, 用户关注此二维码后, 将转到楼房查询页面
	 * 
	 * @param loginUserId
	 * @param width
	 * @param height
	 * @return
	 * @throws Exception
	 */
	@Rest(simpleServiceName = "anonymity", type = "free")
	public Result showBuildingQRCode(String buildingInfoId, int width, int height) throws Exception {
		if (StringUtils.isEmpty(buildingInfoId)) {
			return null;
		}
		
		Integer sceneId = qrLimitSceneService.applySceneId(WeixinService.LIMIT_SUBSCRIBE_KEY_SHOWBUILDING, buildingInfoId);
		
		String url = weixinUtil.createQRCode(null, sceneId, WeixinService.LIMIT_SUBSCRIBE_KEY_SHOWBUILDING, null);
		return qrCodeService.show(url, width, height);
	}
	
	/**
	 * 将房间封装
	 * @since4.0
	 * @return
	 */
	public BuildingFloorRoomVO getBuildRooms() {
		//return buildTestData();
		
		BuildingFloorRoomVO result = new BuildingFloorRoomVO();	
		
		 LandlordUser landlordUser = landlordUserService.getLoginUser();
		 List<Building> buildings = searchBuilding();
		DaRoom dbdaRoom = new DaRoom();
		dbdaRoom.setLandlordUser(landlordUser.getOwnerUser());
		dbdaRoom.setRentState(DaRoom.RENT_STATE_RENT);
		
		 List<DaRoom> daRooms = daRoomService.searchDaRooms(dbdaRoom);
		 for (DaRoom daRoom : daRooms) {
			 SimpleDaRoom daroom = new SimpleDaRoom(daRoom.getId(), daRoom.getName());
			result.getDaRooms().add(daroom);
		}
		 
		 SimpleBuild simpleBuild;
		 for (Building building : buildings) 
		 {
			 simpleBuild = new SimpleBuild();
			 simpleBuild.setName(building.getName());
			 
			 List<BuildingFloor> floors = building.getBuildingFloors();
			 for (BuildingFloor buildingFloor : floors) 
			 {
				SimpleFloor simpleFloor = new SimpleFloor();
				simpleFloor.setName(buildingFloor.getName());

				 Room searchRoom = new Room();
				 searchRoom.setBuildingFloor(buildingFloor);
				 List<Room> roomsOfFloor = genericService.searchAll(searchRoom, false).getData();
				 for (Room room : roomsOfFloor) 
				 {
					 if(room.getRentState() == Room.RENT_STATE_ALREADY){
						 simpleFloor.getRooms().add(new SimpleRoomVO(room.getId(), room.getName()));
					 }
				}
				 
				simpleBuild.getFloors().add(simpleFloor);
			}
			 result.getCaBuildRooms().add(simpleBuild);
		}
		 
		 return result;
	}
	
	/**
	 * 给指定的楼房ID生成普通二维码, 用户扫描该二维码后, 将转到楼房查询手机版页面（包含微信关注临时二维码）
	 * 
	 * @param buildingId 楼ID
	 * @param width
	 * @param height
	 * @return
	 * @throws Exception
	 */
	@Rest(simpleServiceName = "anonymity", type = "free")
	public Result showBuildingGeneralQRCode(String buildingId, int width, int height) throws Exception {
		String url = "http://www.hhz360.com/ra/wap/wap.searchRoomInfoByBuildingId.html?buildingId=" + buildingId;
		return qrCodeService.show(url, width, height);
	}
	
	/**
	 * 用户扫描二维码后，进入手机版页面展示微信关注临时二维码，长按指纹关注并查询该楼房源信息
	 * 
	 * @param buildingId 楼ID
	 * @param width 二维码宽度
	 * @param height 二维码高度
	 * @return
	 * @throws Exception
	 */
	@Rest(simpleServiceName = "anonymity", type = "free")
	public void showBuildingWeixinQRCode(Integer buildingId, int width, int height) throws Exception {
		if (buildingId != null) {
			String url = weixinUtil.createQRCode(WeixinService.SUBSCRIBE_KEY_SHOWBUILDING, buildingId, null, null);
			qrCodeService.show(url, width, height);
		}
	}
	
	/**
	 * 将楼层交换顺序
	 * @param buildingId
	 * @return
	 */
	@Transactional
	public boolean revertBuildingFloorId(Integer buildingId) {
		Building dbBuilding = genericService.load(Building.class, buildingId);
		if (dbBuilding == null) {
			return false;
		}
		List<BuildingFloor> buildingFloors = dbBuilding.getBuildingFloors();
		int buildingFloorSize = buildingFloors.size();
		for (int i = 0; i < buildingFloorSize / 2; i++) {
			BuildingFloor smallerBuildingFloor = buildingFloors.get(i);
			BuildingFloor biggerBuildingFloor = buildingFloors.get(buildingFloorSize - i - 1);
			
			Room smallerRoomExample = new Room();
			smallerRoomExample.setBuildingFloor(smallerBuildingFloor);
			Room biggerRoomExample = new Room();
			biggerRoomExample.setBuildingFloor(biggerBuildingFloor);
			List<Room> smallerRooms = genericService.searchByModel(smallerRoomExample, Condition.DEFAULT, false, true).getData();
			List<Room> biggerRooms = genericService.searchByModel(biggerRoomExample, Condition.DEFAULT, false, true).getData();
		
			BuildingFloor tmpBuildingFloor = new BuildingFloor();
			ModelUtil.copy(smallerBuildingFloor, tmpBuildingFloor);
			smallerBuildingFloor.setNo(biggerBuildingFloor.getNo());
			smallerBuildingFloor.setName(biggerBuildingFloor.getName());
			biggerBuildingFloor.setNo(tmpBuildingFloor.getNo());
			biggerBuildingFloor.setName(tmpBuildingFloor.getName());
			
			if (smallerRooms != null) {
				for (Room room : smallerRooms) {
					room.setBuildingFloor(biggerBuildingFloor);
				}
			}
			
			if (biggerRooms != null) {
				for (Room room : biggerRooms) {
					room.setBuildingFloor(smallerBuildingFloor);
				}
			}
		}
		return true;
	}
	
}